package com.example.shujujiegousuanfa.力扣;

public class n2两数相加 {
    public static void main(String[] args) {
        ListNode listNode = new ListNode(2);
        ListNode listNode1 = new ListNode(4, listNode);
        ListNode listNode2 = new ListNode(3, listNode1);


        ListNode listNode3 = new ListNode(5);
        ListNode listNode4 = new ListNode(6, listNode3);
        ListNode listNode5 = new ListNode(4, listNode4);
        ListNode listNode6 = addTwoNumbers(listNode2, listNode5);
        while (listNode6 != null) {
            System.out.println(listNode6.val);
            listNode6 = listNode6.next;
        }
        System.out.println(listNode);
    }

    /**
     * 声明头部、尾部、进位值
     * 遍历2个链表
     * 获取链表1和链表2的遍历和
     * 放入头部或尾部
     * 处理链表的下一步引用
     * 处理最后1次进位值
     *
     * @param l1
     * @param l2
     * @return
     */
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null;
        ListNode tail = null;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int n1 = l1 != null ? l1.val : 0;
            int n2 = l2 != null ? l2.val : 0;
            int sum = n1 + n2 + carry;
            if (head == null) {
                head = new ListNode(sum % 10);
                tail = head;
            } else {
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }
            // 处理进位
            carry = sum / 10;

            if (l1 != null) {
                l1 = l1.next;
            }

            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry > 0) {
            tail.next = new ListNode(carry);
        }
        return head;
    }

}
